import {
    Button,
    Form,
    Input,
    Radio,
    Select,
    Upload,
    message
} from 'antd';
import './index.scss'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { useState } from 'react';
import { addConsult } from '../../../../../utils/httpAllMethods/consultHttp.jsx';
import PageName from '../../../../../components/PageName/index.jsx';
import { useNavigate } from 'react-router-dom';


const { TextArea } = Input;

// 上传图片
const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

const AddTrade = () => {
    const [fileList,setFileList] = useState([])
    const navigate = useNavigate()
    // 上传图片
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();

    // 图片改变
    const handleChange = (info) => {//判断他的类型和大小
        const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png' || info.file.type === 'image/jpg';
        if (!isJpgOrPng) {
            return message.error('只能上传格式为jpeg/jpg/png的图片');
        }
        const isLt2M = info.file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            return message.error('最大只能上传2M的图片');
        }
        //将文件对象转成base64的地址，img才能显示出来
        getBase64(info.file.originFileObj, (url) => {
            setImageUrl(url);
        });

    };
    // 图片上传按钮
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                添加
            </div>
        </div>
    );
    // 阻止默认上传
    const customRequest = () => {
    }


    // 添加
    const addTrade = (values) => {
        //第一步，得到一个formData盒子
        let myFormData = new FormData()
        //第二步，讲文件装到这个盒子里面去  组装数据
        // myFormData.append(内容的名字，内容)  如果这个内容是一个文件，放的就是文件对象
        // myFormData.append('myfile1',values.consult_img.file.originFileObj)
        // myFormData.append('s_name',values.consult_title)
        if (values.consult_img == '') {
            myFormData.append('consult_img', values.consult_img)
        } else {
            myFormData.append('consult_img', values.consult_img.file.originFileObj)
        }

        myFormData.append('consult_content', values.consult_content)
        myFormData.append('consult_key', values.consult_key)
        myFormData.append('consult_source', values.consult_source)
        myFormData.append('consult_status', values.consult_status)
        myFormData.append('consult_title', values.consult_title)
        myFormData.append('consult_type', values.consult_type)
        myFormData.append('publish_name', JSON.parse(sessionStorage.getItem('userInfo')).admin_nickname)

        addConsult(myFormData).then(res => {
            if (res.code === 200) {
                message.success(res.msg)
            }
            navigate('/home/TradeConsult')

        })
    }
    // 取消添加
    const cancelAdd = () => {
        navigate('/home/TradeConsult')
        message.warning('已取消添加')
    }

    return (
        <>
            <PageName name={'发布资讯'} />
            <Form
                className='addForm'
                labelCol={{
                    span: 2,
                }}
                wrapperCol={{
                    span: 6,
                }}
                colon={false}
                layout="horizontal"
                initialValues={{
                    consult_title: '',
                    consult_source: '',
                    consult_type: '房产资讯',
                    consult_img: '',
                    consult_key: '',
                    consult_status: '发布'
                }}
                onFinish={addTrade}
            >

                <Form.Item
                    label="标题"
                    name="consult_title"
                    rules={[
                        {
                            required: true,
                            message: '请输入资讯标题'
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item label="来源" name="consult_source">
                    <Input />
                </Form.Item>
                <Form.Item
                    label="分类"
                    name="consult_type"
                    rules={[
                        {
                            required: true,
                            message: '请选择资讯分类'
                        },
                    ]}
                    wrapperCol={{
                        span: 3
                    }}
                >
                    <Select>
                        <Select.Option value="房产资讯">房产资讯</Select.Option>
                        <Select.Option value="政策解读">政策解读</Select.Option>
                        <Select.Option value="行业动态">行业动态</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item
                    label="封面图"
                    name='consult_img'
                >
                    <Upload
                        fileList = {fileList}
                        name="avatar"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action=""
                        onChange={handleChange}
                        customRequest={customRequest}
                    >
                        {imageUrl ? (
                            <img
                                src={imageUrl}
                                alt="avatar"
                                style={{
                                    width: '100%',
                                }}
                            />
                        ) : (
                            uploadButton
                        )}
                    </Upload>
                </Form.Item>
                <Form.Item label="关键词" name='consult_key'>
                    <Input />
                </Form.Item>
                <Form.Item
                    label="正文"
                    name='consult_content'
                    rules={[
                        {
                            required: true,
                            message: '请输入资讯正文'
                        },
                    ]}
                >
                    <TextArea rows={4} />
                    {/* import ReactQuill from "react-quill"; */}
                </Form.Item>

                <Form.Item label="发布" name='consult_status'>
                    <Radio.Group>
                        <Radio value="发布"> 发布 </Radio>
                        <Radio value="草稿"> 草稿 </Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item label="发布">
                    <Button type={'primary'} htmlType="submit">确定</Button>
                    <Button type={'default'} className='cancel' onClick={() => {
                        cancelAdd()
                    }}>取消</Button>
                </Form.Item>
            </Form>
        </>
    )
}
export default AddTrade